package com.nisco.dms.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.nisco.dms.entity.Menu;
import com.nisco.dms.entity.Permission;
import com.nisco.dms.entity.Program;
import com.nisco.dms.entity.Role;
import com.nisco.dms.entity.RolePermission;
import com.nisco.dms.service.MenuService;
import com.nisco.dms.service.PermissionService;
import com.nisco.dms.service.ProgramService;
import com.nisco.dms.service.RolePermissionService;
import com.nisco.dms.service.RoleService;
import com.nisco.dms.util.ControllerUtil;
import com.nisco.dms.util.dwz.AjaxObject;
import com.nisco.dms.util.dwz.Page;

@Controller
@RequestMapping(value = "/role")
public class RoleController {
	@Autowired
	private RoleService roleService;

	@Autowired
	private MenuService moduleService;
	
	@Autowired
	private ProgramService programService;

	@Autowired
	private PermissionService permissionService;

	@Autowired
	private RolePermissionService rolePermissionService;

	private static final String CREATE = "role/roleCreate";
	private static final String UPDATE = "role/roleUpdate";
	private static final String LIST = "role/roleList";
	private static final String LIST_TREE = "role/roleListTree";
	private static final String ALTER_PREMISSION = "role/rolePremission";
	private static String  moduleListNavId = "";
	private String strMenuId = "";

	@RequiresPermissions("Role:save")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String preCreate(Map<String, Object> map) {
		map.put("module", moduleService.getTree());
		return CREATE;
	}

	// 重新组装PermissionList（切分test:save,test:edit的形式）
	private void refactor(Role role) {
		List<RolePermission> allList = Lists.newArrayList();
		List<RolePermission> list = role.getPermissionList();
		for (RolePermission rolePermission : list) {
			String strPermission = rolePermission.getStrPermission();
			if ("".equals(strPermission)|| ObjectUtils.equals(strPermission, null))
				continue;
			else {
				if (strPermission.contains(",")) {
					String str[] = strPermission.split(",");
					for (String string : str) {
						RolePermission newRolePermission = new RolePermission();
						newRolePermission.setRoleId(rolePermission.getRoleId());
						newRolePermission.setStrPermission(string);
						allList.add(newRolePermission);
					}

				} else
					allList.add(rolePermission);
			}
		}
		role.setPermissionList(allList);
	}

	@RequiresPermissions("Role:save")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public @ResponseBody
	String create(Role role) {
		refactor(role);
		roleService.save(role);

		AjaxObject ajaxObject = new AjaxObject("角色添加成功！");
		ajaxObject.setNavTabId(moduleListNavId);
		return ajaxObject.toString();
	}

	@RequiresPermissions("Role:edit")
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String preUpdate(@PathVariable String id, Map<String, Object> map) {
		Role role = roleService.get(id);

		map.put("module", moduleService.getTree());
		map.put("role", role);
		return UPDATE;
	}

	@RequiresPermissions("Role:edit")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public @ResponseBody
	String update(Role role) {
		refactor(role);
		roleService.update(role);

		AjaxObject ajaxObject = new AjaxObject("角色修改成功！");
		ajaxObject.setNavTabId(moduleListNavId);
		return ajaxObject.toString();
	}

	@RequiresPermissions("Role:edit")
	@RequestMapping(value = "/alterPremission/{id}", method = RequestMethod.GET)
	public String preAlterPremission(@PathVariable String id,
			Map<String, Object> map) {
		Role role = roleService.get(id);

		map.put("module", moduleService.getTree());
		map.put("role", role);
		return ALTER_PREMISSION;
	}

	@RequiresPermissions("Role:edit")
	@RequestMapping(value = "/alterPremission", method = RequestMethod.POST)
	public @ResponseBody
	String alterPremission(Role role) {
		List<RolePermission> pist = role.getPermissionList();
		for(int i=0;i<pist.size();i++){
			if(pist.get(i).getStrPermission() == null){
				pist.remove(i);
			}
		}
		if (!strMenuId.equals("")) {
			String strSn = moduleService.get(strMenuId)==null?programService.get(strMenuId).getStrSn():moduleService.get(strMenuId).getStrSn();
			for(int i =0;i<permissionService.findAll().size();i++){
				rolePermissionService.deleRolePermissionByRoleId(role.getId(),strSn + ":"+permissionService.findAll().get(i).getStrName());
			}
		} 
		List<RolePermission> pist2 = rolePermissionService.findByRoleId(role.getId());
		pist2.addAll(pist);

		role.setPermissionList(pist2);
		roleService.update(role);

		AjaxObject ajaxObject = new AjaxObject("角色权限修改成功！");
		ajaxObject.setNavTabId(moduleListNavId);
		return ajaxObject.toString();
	}

	@RequiresPermissions("Role:delete")
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	public @ResponseBody
	String delete(@PathVariable String id) {

		roleService.delete(id);

		AjaxObject ajaxObject = new AjaxObject("角色删除成功！");
		ajaxObject.setCallbackType("");
		return ajaxObject.toString();
	}

	@RequiresPermissions("Role:view")
	@RequestMapping(value = "/list", method = { RequestMethod.GET,RequestMethod.POST })
	public String list(Page page, String keywords, Map<String, Object> map,HttpServletRequest request) {
		moduleListNavId = ControllerUtil.navId(moduleListNavId, (String)request.getParameter("moduleListNavId"));
		List<Role> roles = null;
		if (StringUtils.isNotBlank(keywords)) {
			roles = roleService.find(page, keywords);
		} else {
			roles = roleService.findAll(page);
		}

		map.put("page", page);
		map.put("roles", roles);
		map.put("keywords", keywords);
		return LIST;
	}

	@RequiresPermissions("Role:view")
	@RequestMapping(value = "/list/{programId}/{roleId}", method = {RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String list(@PathVariable String programId,@PathVariable String roleId, String keywords,Map<String, Object> map, HttpServletRequest request) {
		strMenuId = programId;

		// 1、根据模块ID取得当前模块
		Program module = programService.findOne(programId);
		// 2、根据模块取得该模块对应的按钮的权限
		List<Permission> permissions = permissionService
				.findByModuleId(programId);
		// 3、根据角色Id取得当前角色
		Role role = roleService.get(roleId);
		// 4、根据当前Id取得当前角色已有的模块按钮权限
		List<RolePermission> pist = role.getPermissionList();
		List<String> permissionList = new ArrayList<String>();
		for (int i = 0; i < pist.size(); i++) {
			permissionList.add(pist.get(i).getStrPermission());
		}

		// 5、根据角色已有的相应权限组装权限树

		StringBuffer permissionTree = new StringBuffer();
		if (permissions.size() != 0) {
			for (int i = 0; i < permissions.size(); i++) {
				if (permissionList.contains(module.getStrSn() + ":"+ permissions.get(i).getStrName())) {
					permissionTree.append("<input type=\"checkbox\" name=\"permissionList["
									+ i
									+ "].strPermission\" value=\""
									+ module.getStrSn()
									+ ":"
									+ permissions.get(i).getStrName()
									+ "\" checked=\"checked\"/>"
									+ "&nbsp;<a>"
									+permissions.get(i).getStrName()+"[" +permissions.get(i).getStrDesc()
									+ "]</a><br/>");
				} else {
					permissionTree.append("<input type=\"checkbox\" name=\"permissionList["
									+ i
									+ "].strPermission\" value=\""
									+ module.getStrSn()
									+ ":"
									+ permissions.get(i).getStrName()
									+ "\"/>"
									+ "&nbsp;<a>"
									+ permissions.get(i).getStrName()+"[" +permissions.get(i).getStrDesc()
									+ "]</a><br/>");
				}
			}
		} else {
			if (module != null) {
				permissionTree.append("提示：<br/>角色" + role.getStrName() + "没有操作"+ module.getStrName() + "下相应按钮的权限。<br/>请联系管理员添加。");
			} else {
				Menu menu = moduleService.get(programId);
				if (permissionList.contains(menu.getStrSn() + ":view")) {
					permissionTree.append("<input type=\"checkbox\" name=\"permissionList[0].strPermission\" value=\""
									+ menu.getStrSn()
									+ ":view\" checked=\"checked\"/>"
									+ "&nbsp;<a>界面管理</a><br/>");
				} else {
					permissionTree.append("<input type=\"checkbox\" name=\"permissionList[0].strPermission\" value=\""
									+ menu.getStrSn()
									+ ":view\"/>"
									+ "&nbsp;<a>界面管理</a><br/>");
				}
			}
		}
		//map.put("permissionTree", permissionTree);

		return permissionTree.toString();
	}
}
